package com.yangleping.dynamic.thread.pool.sdk.trigger.listener;

import com.yangleping.dynamic.thread.pool.sdk.domain.IDynamicThreadPoolService;
import com.yangleping.dynamic.thread.pool.sdk.domain.model.ThreadPoolConfigEntity;
import com.yangleping.dynamic.thread.pool.sdk.registry.IRegistry;
import org.redisson.api.listener.MessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class ThreadPoolConfigAdjustListener implements MessageListener<ThreadPoolConfigEntity> {

    private Logger logger = LoggerFactory.getLogger(ThreadPoolConfigAdjustListener.class);

    private final IDynamicThreadPoolService dynamicThreadPoolService;

    private final IRegistry registry;

    public ThreadPoolConfigAdjustListener(IDynamicThreadPoolService dynamicThreadPoolService, IRegistry registry) {
        this.dynamicThreadPoolService = dynamicThreadPoolService;
        this.registry = registry;
    }

    @Override
    public void onMessage(CharSequence charSequence, ThreadPoolConfigEntity threadPoolConfigEntity) {
        logger.info("动态线程池，配置更新, 线程池名：{} 池化配置：{}", threadPoolConfigEntity.getThreadPoolName(), threadPoolConfigEntity);
        dynamicThreadPoolService.updateThreadPoolConfig(threadPoolConfigEntity);

        //更新后上报最新数据
        List<ThreadPoolConfigEntity> threadPoolConfigEntities = dynamicThreadPoolService.queryThreadPoolList();
        registry.reportThreadPool(threadPoolConfigEntities);

        ThreadPoolConfigEntity configEntity = dynamicThreadPoolService.queryThreadPoolConfigByName(threadPoolConfigEntity.getThreadPoolName());
        registry.reportThreadPoolConfigParameter(configEntity);
    }
}
